{{- define "deckhouse_resources" }}
cpu: 500m
memory: 1000Mi
{{- end }}

{{- if and (.Values.global.enabledModules | has "vertical-pod-autoscaler-crd") (.Capabilities.APIVersions.Has "autoscaling.k8s.io/v1/VerticalPodAutoscaler") }}
---
apiVersion: autoscaling.k8s.io/v1
kind: VerticalPodAutoscaler
metadata:
  name: deckhouse
  namespace: d8-system
  {{- if .Values.deckhouse.nodeSelector }}
  {{- include "helm_lib_module_labels" (list . (dict "app" "deckhouse")) | nindent 2 }}
  {{- else }}
  {{- include "helm_lib_module_labels" (list . (dict "app" "deckhouse" "workload-resource-policy.deckhouse.io" "master")) | nindent 2 }}
  {{- end }}
spec:
  targetRef:
    apiVersion: "apps/v1"
    kind: Deployment
    name: deckhouse
  updatePolicy:
    updateMode: "Initial"
  resourcePolicy:
    containerPolicies:
    - containerName: deckhouse
      minAllowed:
        {{- include "deckhouse_resources" . | nindent 8 }}
      maxAllowed:
        cpu: 1000m
        memory: 2000Mi
    {{- include "helm_lib_vpa_kube_rbac_proxy_resources" . | nindent 4 }}
{{- end }}
---
apiVersion: policy/v1
kind: PodDisruptionBudget
metadata:
  name: deckhouse
  namespace: d8-system
  {{- include "helm_lib_module_labels" (list . (dict "app" "deckhouse")) | nindent 2 }}
spec:
  maxUnavailable: 1
  selector:
    matchLabels:
      app: deckhouse
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: deckhouse
  namespace: d8-system
  annotations:
    helm.sh/resource-policy: keep
    core.deckhouse.io/version: {{ .Values.global.deckhouseVersion | quote }}
    core.deckhouse.io/edition: {{ .Values.global.deckhouseEdition | quote }}
  {{- include "helm_lib_module_labels" (list . (dict "app" "deckhouse")) | nindent 2 }}
spec:
  {{- include "helm_lib_deployment_on_master_custom_strategy_and_replicas_for_ha" (list . (dict "strategy" "Recreate")) | nindent 2 }}
  revisionHistoryLimit: 2
  selector:
    matchLabels:
      app: deckhouse
  template:
    metadata:
      labels:
        app: deckhouse
      annotations:
        checksum/registry: {{ include (print $.Template.BasePath "/registry-secret.yaml") . | sha256sum }}
    spec:
{{- if (include "helm_lib_ha_enabled" .) }}
      affinity:
        podAntiAffinity:
          preferredDuringSchedulingIgnoredDuringExecution:
            - podAffinityTerm:
                labelSelector:
                  matchExpressions:
                    - key: app
                      operator: In
                      values:
                        - deckhouse
                topologyKey: kubernetes.io/hostname
              weight: 100
{{- end }}
{{- include "helm_lib_priority_class" (tuple . "system-cluster-critical") | nindent 6 }}
{{- if .Values.deckhouse.nodeSelector }}
      nodeSelector:
        {{- .Values.deckhouse.nodeSelector | toYaml | nindent 8 }}
{{- else }}
      {{- include "helm_lib_node_selector" (tuple . "master") | nindent 6 }}
{{- end }}
{{- if .Values.deckhouse.tolerations }}
      tolerations:
        {{- .Values.deckhouse.tolerations | toYaml | nindent 8 }}
{{- else }}
      {{- include "helm_lib_tolerations" (tuple . "wildcard") | nindent 6 }}
{{- end }}
      {{- include "helm_lib_module_pod_security_context_run_as_user_deckhouse" . | nindent 6 }}
{{- if (.Values.global.enabledModules | has "external-module-manager") }}
      initContainers:
        - name: init-external-modules
          image: {{ include "helm_lib_module_common_image" (list . "alpine") }}
          imagePullPolicy: Always
          command: ['sh', '-c', 'mkdir -p /deckhouse/external-modules/modules && chown -hR 64535 /deckhouse/external-modules /deckhouse/external-modules/modules && chmod 0700 /deckhouse/external-modules /deckhouse/external-modules/modules']
          securityContext:
            runAsUser: 0
            runAsNonRoot: false
          resources:
            requests:
              {{- include "helm_lib_module_ephemeral_storage_logs_with_extra" 100 | nindent 14 }}
          volumeMounts:
            - mountPath: /deckhouse/external-modules
              name: external-modules
{{- end }}
      containers:
        - name: deckhouse
          {{- include "helm_lib_module_container_security_context_read_only_root_filesystem_with_selinux" . | nindent 10 }}
          command:
            - /deckhouse/deckhouse
          image: "{{ .Values.deckhouse.internal.currentReleaseImageName }}"
          imagePullPolicy: Always
          env:
# KUBERNETES_SERVICE_HOST and KUBERNETES_SERVICE_PORT are needed on the bootstrap phase to make Deckhouse work without kube-proxy
{{- if not .Values.global.clusterIsBootstrapped }}
            - name: KUBERNETES_SERVICE_HOST
              valueFrom:
                fieldRef:
                  apiVersion: v1
                  fieldPath: status.hostIP
            - name: KUBERNETES_SERVICE_PORT
              value: "6443"
{{- end }}
            - name: LOG_LEVEL
              value: {{ .Values.deckhouse.logLevel }}
            - name: LOG_TYPE
              value: "json"
            - name: DECKHOUSE_HA
{{- if and (include "helm_lib_ha_enabled" .) .Values.global.clusterIsBootstrapped }}
              value: "true"
            - name: KUBERNETES_CLUSTER_DOMAIN
              value: {{ .Values.global.clusterConfiguration.clusterDomain | quote }}
{{- else }}
              value: "false"
{{- end }}
            - name: DECKHOUSE_BUNDLE
              value: {{ .Values.deckhouse.bundle }}
            - name: DECKHOUSE_POD
              valueFrom:
                fieldRef:
                  fieldPath: metadata.name
            - name: DECKHOUSE_NODE_NAME
              valueFrom:
                fieldRef:
                  fieldPath: spec.nodeName
            - name: HELM_HOST
              value: "127.0.0.1:44434"
            - name: OBJECT_PATCHER_KUBE_CLIENT_QPS
              value: "30"
            - name: OBJECT_PATCHER_KUBE_CLIENT_BURST
              value: "60"
            - name: KUBE_CLIENT_QPS
              value: "20"
            - name: KUBE_CLIENT_BURST
              value: "40"
            - name: ADDON_OPERATOR_PROMETHEUS_METRICS_PREFIX
              value: deckhouse_
            - name: ADDON_OPERATOR_NAMESPACE
              valueFrom:
                fieldRef:
                  fieldPath: metadata.namespace
            - name: ADDON_OPERATOR_LISTEN_ADDRESS
              valueFrom:
                fieldRef:
                  fieldPath: status.podIP
            - name: ADDON_OPERATOR_ADMISSION_SERVER_ENABLED
              value: "true"
            - name: ADDON_OPERATOR_ADMISSION_SERVER_CERTS_DIR
              value: "/certs"
            - name: HELM3LIB
              value: "yes"
            - name: HELM_HISTORY_MAX
              value: "3"
{{- if (.Values.global.enabledModules | has "external-module-manager") }}
            - name: MODULES_DIR
              value: "/deckhouse/modules:/deckhouse/external-modules/modules"
            - name: EXTERNAL_MODULES_DIR
              value: "/deckhouse/external-modules/"
{{- else }}
            - name: MODULES_DIR
              value: "/deckhouse/modules"
{{- end }}
            - name: DEBUG_UNIX_SOCKET
              value: /tmp/shell-operator-debug.socket
            - name: HISTFILE
              value: /tmp/.bash_history
            - name: DEBUG_HTTP_SERVER_ADDR
              value: "127.0.0.1:9652"
            {{- include "helm_lib_envs_for_proxy" . | nindent 12 }}
          ports:
            - containerPort: 9650
              name: self
            - containerPort: 9651
              name: webhook
          readinessProbe:
            httpGet:
              path: /readyz
              port: 9650
            initialDelaySeconds: 5
            # fail after 10 minutes
            periodSeconds: 5
            failureThreshold: 120
          resources:
            requests:
              {{- include "helm_lib_module_ephemeral_storage_logs_with_extra" 100 | nindent 14 }}
{{- if not ( .Values.global.enabledModules | has "vertical-pod-autoscaler-crd") }}
              {{- include "deckhouse_resources" . | nindent 14 }}
{{- end }}
          workingDir: /deckhouse
          volumeMounts:
          - mountPath: /tmp
            name: tmp
          - mountPath: /.kube
            name: kube
          - mountPath: /certs
            name: certs
            readOnly: true
{{- if (.Values.global.enabledModules | has "external-module-manager") }}
          - mountPath: /deckhouse/external-modules
            name: external-modules
{{- end }}
        - name: kube-rbac-proxy
          {{- include "helm_lib_module_container_security_context_read_only_root_filesystem" . | nindent 10 }}
          image: {{ include "helm_lib_module_common_image" (list $ "kubeRbacProxy") }}
          args:
          - "--secure-listen-address=$(KUBE_RBAC_PROXY_LISTEN_ADDRESS):9889"
          - "--v=2"
          - "--logtostderr=true"
          - "--stale-cache-interval=1h30m"
          - "--livez-path=/livez"
          env:
          - name: KUBE_RBAC_PROXY_LISTEN_ADDRESS
            valueFrom:
              fieldRef:
                fieldPath: status.hostIP
          - name: KUBE_RBAC_PROXY_CONFIG
            value: |
              upstreams:
              - upstream: http://127.0.0.1:9652
                path: /
                authorization:
                  resourceAttributes:
                    namespace: d8-system
                    apiGroup: apps
                    apiVersion: v1
                    resource: deployment
                    subresource: http
                    name: debugSrv
          ports:
          - containerPort: 9889
            name: https
          livenessProbe:
            httpGet:
              path: /livez
              port: 9889
              scheme: HTTPS
          readinessProbe:
            httpGet:
              path: /livez
              port: 9889
              scheme: HTTPS
          resources:
            requests:
              {{- include "helm_lib_module_ephemeral_storage_only_logs" . | nindent 14 }}
{{- if not ( .Values.global.enabledModules | has "vertical-pod-autoscaler-crd") }}
              {{- include "helm_lib_container_kube_rbac_proxy_resources" . | nindent 14 }}
{{- end }}
      hostNetwork: true
{{- if .Values.global.clusterIsBootstrapped }}
      dnsPolicy: ClusterFirstWithHostNet
{{- else }}
      dnsPolicy: Default
{{- end}}
      serviceAccountName: deckhouse
      volumes:
      - emptyDir:
          medium: Memory
        name: tmp
      - emptyDir:
          medium: Memory
        name: kube
      - name: certs
        secret:
          secretName: admission-webhook-certs
{{- if (.Values.global.enabledModules | has "external-module-manager") }}
      - name: external-modules
        hostPath:
          path: /var/lib/deckhouse/external-modules
          type: DirectoryOrCreate
{{- end}}
